class CharacterSettings {
  constructor(onChange) {
    this.onChange = onChange;
    this.form = document.createElement('form');
    this.setupForm();
  }

  setupForm() {
    // 角色名称
    const nameField = this.createField('角色名称', 'text', 'name');
    this.form.appendChild(nameField);

    // 角色头像
    const avatarField = this.createField('角色头像', 'file', 'avatar');
    this.form.appendChild(avatarField);

    // 性格特征
    const personalityField = this.createTextareaField('性格特征', 'personality');
    this.form.appendChild(personalityField);

    // 说话风格
    const styleField = this.createTextareaField('说话风格', 'style');
    this.form.appendChild(styleField);

    // 提交按钮
    const submitButton = document.createElement('button');
    submitButton.type = 'submit';
    submitButton.textContent = '保存设置';
    this.form.appendChild(submitButton);

    // 表单提交事件
    this.form.addEventListener('submit', async (e) => {
      e.preventDefault();
      const formData = new FormData(this.form);
      
      // 处理avatar文件
      const avatarFile = formData.get('avatar');
      let avatarBase64 = this.form.avatar.value; // 获取当前avatar值
      
      // 如果有新上传的文件，转换为base64
      if (avatarFile && avatarFile.size > 0) {
        avatarBase64 = await new Promise((resolve) => {
          const reader = new FileReader();
          reader.onload = () => resolve(reader.result);
          reader.readAsDataURL(avatarFile);
        });
      }

      const settings = {
        name: formData.get('name') || this.form.name.value,
        personality: formData.get('personality') || this.form.personality.value,
        style: formData.get('style') || this.form.style.value,
        avatar: avatarBase64 || this.form.querySelector('.avatar-preview')?.src || '' // 确保avatar不为空
      };
      
      this.onChange(settings);
    });
  }

  createField(labelText, type, name) {
    const container = document.createElement('div');
    container.classList.add('form-field');

    const label = document.createElement('label');
    label.textContent = labelText;
    container.appendChild(label);

    const input = document.createElement('input');
    input.type = type;
    input.name = name;
    container.appendChild(input);

    // 如果是头像字段，添加预览元素
    if (name === 'avatar') {
      const preview = document.createElement('img');
      preview.classList.add('avatar-preview');
      preview.style.display = 'none';
      container.appendChild(preview);

      input.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = (event) => {
            preview.src = event.target.result;
            preview.style.display = 'block';
          };
          reader.readAsDataURL(file);
        }
      });
    }

    return container;
  }

  createTextareaField(labelText, name) {
    const container = document.createElement('div');
    container.classList.add('form-field');

    const label = document.createElement('label');
    label.textContent = labelText;
    container.appendChild(label);

    const textarea = document.createElement('textarea');
    textarea.name = name;
    container.appendChild(textarea);

    return container;
  }

  async update(characterData) {
    if (!characterData) {
      characterData = {
        name: '',
        personality: '',
        style: '',
        avatar: ''
      };
    }
    this.form.name.value = characterData.name || '';
    this.form.personality.value = characterData.personality || '';
    this.form.style.value = characterData.style || '';
    
    // 处理头像
    const avatarPreview = this.form.querySelector('.avatar-preview');
    if (avatarPreview) {
      // 处理avatar数据
      if (characterData.avatar) {
        // 如果是File对象，读取为Data URL
        if (characterData.avatar instanceof File) {
          const reader = new FileReader();
          reader.onload = (e) => {
            avatarPreview.src = e.target.result;
            avatarPreview.style.display = 'block';
          };
          reader.readAsDataURL(characterData.avatar);
        }
        // 如果是字符串，直接使用
        else if (typeof characterData.avatar === 'string') {
          avatarPreview.src = characterData.avatar;
          avatarPreview.style.display = 'block';
        }
      } else {
        // 如果没有avatar数据，使用默认头像
        avatarPreview.src = 'default-avatar.png';
        avatarPreview.style.display = 'block';
        this.form.avatar.value = '';
      }
    }
  }

  getCurrentSettings() {
    const avatarPreview = this.form.querySelector('.avatar-preview');
    return {
      name: this.form.name.value,
      personality: this.form.personality.value,
      style: this.form.style.value,
      avatar: avatarPreview?.src || ''
    };
  }

  render() {
    return this.form;
  }
}

export default CharacterSettings;
